<template>
  <div class="post-detail">
    <!-- 帖子内容 -->
    <el-card v-loading="loading" class="post-card">
      <template v-if="post">
        <div class="post-header">
          <div class="user-info">
            <el-avatar 
              :size="40" 
              :src="getAvatarUrl(post.avatar)"
            ></el-avatar>
            <div class="info-text">
              <span class="username">{{ post.userName }}</span>
              <span class="time">{{ post.createTime }}</span>
            </div>
          </div>
          <div class="post-stats">
            <el-tag size="small">{{ post.categoryName }}</el-tag>
            <span class="stat-item">
              <el-icon><View /></el-icon>
              {{ post.viewCount }}
            </span>
            <span class="stat-item">
              <el-icon><ChatDotRound /></el-icon>
              {{ post.commentCount }}
            </span>
            <el-button
              v-if="post.userId === userId"
              type="primary"
              link
              @click="handleEdit"
            >
              编辑
            </el-button>
          </div>
        </div>
        <div class="post-content">
          <h2 class="post-title">{{ post.title }}</h2>
          <div class="post-text">{{ post.content }}</div>
          <div v-if="post.images" class="post-images">
            <el-image
              v-for="(image, index) in parseImages(post.images)"
              :key="index"
              :src="getImageUrl(image)"
              :preview-src-list="parseImages(post.images).map(img => getImageUrl(img))"
              fit="cover"
              class="preview-image"
            />
          </div>
        </div>
      </template>
    </el-card>

    <!-- 评论区 -->
    <el-card class="comment-card">
      <template #header>
        <div class="comment-header">
          <span>评论 ({{ post?.commentCount || 0 }})</span>
        </div>
      </template>

      <!-- 评论输入框 -->
      <div class="comment-input">
        <el-input
          v-model="commentContent"
          type="textarea"
          :rows="3"
          placeholder="写下你的评论..."
        />
        <el-button
          type="primary"
          :loading="submitting"
          @click="submitComment"
          style="margin-top: 10px"
        >
          发表评论
        </el-button>
      </div>

      <!-- 评论列表 -->
      <div class="comment-list">
        <div v-if="comments.length" class="comment-items">
          <div
            v-for="comment in comments"
            :key="comment.commentId"
            class="comment-item"
          >
            <div class="comment-user">
              <el-avatar :size="32" :src="getAvatarUrl(comment.avatar)"></el-avatar>
              <div class="comment-info">
                <span class="comment-username">{{ comment.userName }}</span>
                <span class="comment-time">{{ comment.createTime }}</span>
              </div>
              <el-button
                v-if="comment.userId === userId"
                type="danger"
                link
                @click="handleDeleteComment(comment.commentId)"
              >
                删除
              </el-button>
            </div>
            <div class="comment-content">{{ comment.content }}</div>
          </div>
        </div>
        <el-empty v-else description="暂无评论" />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { View, ChatDotRound } from '@element-plus/icons-vue'
import { getPost } from '@/api/ich/forum'
import { listComment, addComment, delComment } from '@/api/ich/comment'
import useUserStore from '@/store/modules/user'

const route = useRoute()
const router = useRouter()
const store = useUserStore()

const loading = ref(false)
const submitting = ref(false)
const post = ref(null)
const comments = ref([])
const commentContent = ref('')
const userId = ref(store.id)

// 添加基础URL
const baseUrl = import.meta.env.VITE_APP_BASE_API

// 处理头像URL
const getAvatarUrl = (avatar) => {
  if (!avatar) return '/avatar.png'
  if (avatar.startsWith('http')) return avatar
  return baseUrl + avatar
}

// 处理图片URL
const getImageUrl = (image) => {
  if (!image) return ''
  if (image.startsWith('http')) return image
  return baseUrl + image
}

// 获取帖子详情
const getPostDetail = async () => {
  loading.value = true
  try {
    const res = await getPost(route.params.id)
    if (res.code === 200) {
      post.value = res.data
      // 确保图片数据正确处理
      if (post.value.images) {
        console.log('原始图片数据:', typeof post.value.images === 'string' ? 
          JSON.parse(post.value.images) : post.value.images)
        const processedImages = parseImages(post.value.images)
        console.log('处理后的图片数据:', processedImages)
      }
      // 获取评论列表
      getCommentList()
    } else {
      ElMessage.error(res.msg || '获取帖子详情失败')
    }
  } catch (error) {
    console.error('获取帖子详情失败:', error)
    ElMessage.error('获取帖子详情失败')
  } finally {
    loading.value = false
  }
}

// 获取评论列表
const getCommentList = async () => {
  try {
    const res = await listComment({
      postId: route.params.id
    })
    if (res.code === 200) {
      comments.value = res.rows
    } else {
      ElMessage.error(res.msg || '获取评论列表失败')
    }
  } catch (error) {
    console.error('获取评论列表失败:', error)
    ElMessage.error('获取评论列表失败')
  }
}

// 提交评论
const submitComment = async () => {
  if (!commentContent.value.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }

  submitting.value = true
  try {
    const res = await addComment({
      postId: post.value.postId,
      content: commentContent.value.trim()
    })
    if (res.code === 200) {
      ElMessage.success('评论成功')
      commentContent.value = ''
      // 刷新评论列表和帖子详情
      getPostDetail()
    } else {
      ElMessage.error(res.msg || '评论失败')
    }
  } catch (error) {
    console.error('评论失败:', error)
    ElMessage.error('评论失败')
  } finally {
    submitting.value = false
  }
}

// 删除评论
const handleDeleteComment = async (commentId) => {
  try {
    await ElMessageBox.confirm('确认要删除这条评论吗？', '提示', {
      type: 'warning'
    })
    const res = await delComment(commentId)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      // 刷新评论列表和帖子详情
      getPostDetail()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除评论失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 编辑帖子
const handleEdit = () => {
  router.push(`/user/forum/edit/${post.value.postId}`)
}

// 修改图片解析函数
const parseImages = (images) => {
  if (!images) return []
  
  try {
    let imageArray = []
    // 如果是字符串，尝试解析JSON
    if (typeof images === 'string') {
      imageArray = JSON.parse(images)
    }
    // 如果已经是数组，直接使用
    else if (Array.isArray(images)) {
      imageArray = images
    }
    
    // 过滤掉无效的图片URL
    return imageArray.filter(img => img && typeof img === 'string')
  } catch (error) {
    console.error('解析图片数据失败:', error)
    return []
  }
}

onMounted(() => {
  getPostDetail()
})
</script>

<style lang="scss" scoped>
.post-detail {
  padding: 20px;

  .post-card {
    margin-bottom: 20px;

    .post-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      .user-info {
        display: flex;
        align-items: center;

        .info-text {
          margin-left: 10px;
          display: flex;
          flex-direction: column;

          .username {
            font-weight: bold;
            font-size: 16px;
          }

          .time {
            font-size: 12px;
            color: #999;
          }
        }
      }

      .post-stats {
        display: flex;
        align-items: center;
        gap: 15px;

        .stat-item {
          display: flex;
          align-items: center;
          gap: 5px;
          color: #666;
          font-size: 14px;
        }
      }
    }

    .post-content {
      .post-title {
        margin: 0 0 20px;
        font-size: 24px;
        font-weight: bold;
        color: #2c3e50;
      }

      .post-text {
        margin: 15px 0;
        line-height: 1.6;
        white-space: pre-wrap;
        word-break: break-all;
      }

      .post-images {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
        margin-top: 15px;

        .preview-image {
          width: 200px;
          height: 200px;
          border-radius: 8px;
          object-fit: cover;
          cursor: pointer;
          transition: transform 0.3s ease;

          &:hover {
            transform: scale(1.02);
          }
        }
      }
    }
  }

  .comment-card {
    .comment-header {
      font-size: 18px;
      font-weight: bold;
      color: #2c3e50;
    }

    .comment-input {
      margin-bottom: 20px;
    }

    .comment-list {
      .comment-item {
        padding: 15px 0;
        border-bottom: 1px solid #eee;

        &:last-child {
          border-bottom: none;
        }

        .comment-user {
          display: flex;
          align-items: center;
          margin-bottom: 10px;

          .comment-info {
            margin-left: 10px;
            flex: 1;

            .comment-username {
              font-weight: bold;
              font-size: 14px;
            }

            .comment-time {
              font-size: 12px;
              color: #999;
              margin-left: 10px;
            }
          }
        }

        .comment-content {
          margin-left: 42px;
          color: #333;
          line-height: 1.5;
        }
      }
    }
  }
}
</style>
